package com.bf.electroplating.login;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Field;
import java.util.stream.Collectors;

public class TenantLineInnerInterceptor implements InnerInterceptor {

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter,
                            RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {

        // 如果是登录请求，直接跳过
        String currentRequestPath = getCurrentRequestPath();
        if ("/electroplating/after/login".equals(currentRequestPath)) {
            return;
        }
        if (!needsTenantFilter(ms.getId())) {
            return;
        }

        UserDetail user = UserContext.getUser();
        if (user == null) {
//            throw new RuntimeException("用户未登录");
        }else {

            // 获取原始SQL
            String originalSql = boundSql.getSql();
            String tenantFilter="";
            if (CollectionUtils.isEmpty(user.getParkFunctionIds())) {
                // 构建企业过滤条件
                if ( originalSql.contains("company_id")) {
                    if (ms.getId().contains("ComCompany")) {
                        tenantFilter = " AND ID = " + user.getCompanyId();
                    } else {
                        tenantFilter = " AND COMPANY_ID = " + user.getCompanyId();
                    }
                }
            } else {
                // 构建企业过滤条件
                if (ms.getId().contains("ComCompany")) {
                    tenantFilter = "";
                } else {
                    if (originalSql.contains("PARK_ID")) {
                        String parkIds = user.getParkFunctionIds().stream().map(id -> "'" + id + "'").collect(Collectors.joining(","));
                        String before = " ";
                        tenantFilter = "";
                        if (!originalSql.contains("ORDER BY")) {
                            if (!originalSql.contains("WHERE") && !originalSql.contains("where")) {
                                before = "WHERE ";
                            } else {
                                before = "AND ";
                            }
                            tenantFilter = " " + before + " PARK_ID IN (" + parkIds + ")";
                        }
                    }
                }
            }

            // 自动拼接企业过滤条件（仅对需要过滤的表生效）
            String newSql = enhanceSelectSql(originalSql, tenantFilter);
            // 反射修改SQL
            Field sqlField = null;
            try {
                sqlField = boundSql.getClass().getDeclaredField("sql");
                sqlField.setAccessible(true);
                sqlField.set(boundSql, newSql);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }

    private String getCurrentRequestPath() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            return request.getRequestURI();
        }
        return null;
    }

    // 增强SELECT语句
    private String enhanceSelectSql(String sql, String tenantFilter) {

        // 有WHERE子句，查找del_flag='0'的位置
        String lowerCaseSql = sql.toLowerCase();
        int whereIndex = lowerCaseSql.indexOf("where");
        String delFlagCondition = "del_flag='0'";
        int delFlagIndex = lowerCaseSql.indexOf(delFlagCondition.toLowerCase());

        if (delFlagIndex > whereIndex) {
            // 找到del_flag='0'，在其后添加tenantFilter
            int endIndex = delFlagIndex + delFlagCondition.length();
            return sql.substring(0, endIndex) +
                    tenantFilter +
                    sql.substring(endIndex);
        }

        // 正常情况，直接在WHERE子句后添加条件
        return sql + tenantFilter;
    }

    // 判断是否需要进行企业数据过滤
    private boolean needsTenantFilter(String mapperMethod) {
        if (mapperMethod.contains("InspectionTaskCompany")) {
            return false;
        }
        if (mapperMethod.contains("InspectionTaskFacility")) {
            return false;
        }
        if (mapperMethod.contains("InspectionTaskUser")) {
            return false;
        }
        if (mapperMethod.contains("ControlProblemRectification")) {
            return false;
        }
        if (mapperMethod.contains("ControlRenovateRectification")) {
            return false;
        }
        if (mapperMethod.contains("ParkContingencyTeamPerson")) {
            return false;
        }
        if (mapperMethod.equals("com.bf.electroplating.mapper.ParkContingencyTeamMapper.getTeamPage")) {
            return false;
        }
        if (mapperMethod.contains("Sys")) {
            return false;
        }
        if (mapperMethod.contains("Pub")) {
            return false;
        }
        return true;
    }
}